#!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import g, Flask, request, current_app
from applications.models.user import User
from flask_jwt_extended import JWTManager, get_jwt_identity, verify_jwt_in_request, jwt_required
from functools import wraps

jwt = JWTManager()


def init_jwt(app: Flask):
    """初始化 JWT 插件并挂载当前用户到 g.user"""
    jwt.init_app(app)


    @app.before_request
    def attach_current_user():
        """自动尝试从 JWT 中挂载当前用户到 g.user，可选 token，保证不报错"""
        g.user = None

        auth_header = request.headers.get("Authorization", "").strip()
        if auth_header.startswith("Bearer "):
            try:
                # 只有在 Header 合法时才执行验证
                verify_jwt_in_request()
                user_id = get_jwt_identity()
                if user_id:
                    g.user = User.query.get(user_id)
            except Exception as e:
                # token 无效、过期、篡改等都不会抛错给前端
                current_app.logger.error(f"JWT 验证失败: {str(e)}")
                g.user = None


def jwt_required_with_user():
    """
    用于视图函数的装饰器：
    要求用户必须登录，并挂载 g.user
    """
    def wrapper(fn):
        @wraps(fn)
        @jwt_required()
        def decorated_function(*args, **kwargs):
            user_id = get_jwt_identity()
            user = User.query.get(user_id)
            if not user:
                return {"msg": "用户不存在"}, 401
            g.user = user
            return fn(*args, **kwargs)
        return decorated_function
    return wrapper